<template>
  <div class="app-container">
    <div class="filter-container">
      <el-dialog  v-dialogDrag  
        :close-on-click-modal="false"
        :title="dialogStatus"
        :visible.sync="dialogEditFormVisible"
        style="padding:0px"
        width="28%"
      >
        <div class="auditing">
          <el-row>
            <el-form
              label-position="right"
              label-width="100px"
              class="dialog-Backgroundcolor"
            >
              <el-row>
                <el-col :span="24">
                  <el-select
                    v-model="queryForm.salaryId"
                    class="filter-item"
                  >
                    <!--查询可计算项-->
                    <el-option
                      label="--请选择--"
                      value=""
                    />
                    <template v-for="item in salaryList">
                      <el-option
                        v-if="item.isCompute === 1"
                        :key="item.id"
                        :label="item.salaryName"
                        :value="item.id"
                      />
                    </template>
                  </el-select>

                </el-col>
              </el-row>
              <el-row>
                <el-button
                  style="float:right;"
                  type="primary"
                  @click="handleFilter"
                >
                  查询
                </el-button>
              </el-row>
            </el-form>
          </el-row>
        </div>
      </el-dialog>
      <!-- 切换按钮 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-col :span="1">
            <i :class="[treeShow ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']" @click="toggerTree" />
          </el-col>
        </el-col>
        <!--功能按钮-->
        <div class="filter-container">
          <div class="longbuton">
            <el-col style="text-align:right;margin-top: -3px;" :span="16">
             <el-button size="small" class="filter-item" style="margin-left:10px;" type="primary" @click="CopyFormula">
                复制公式
              </el-button>  
              <el-button size="small" class="filter-item" style="margin-left:10px;" type="primary" @click="Query">
                查询
              </el-button>
              <el-button size="small" class="filter-item" type="primary" style="margin-left:10px;" @click="handleAdd">
                新增
              </el-button>
              <el-button size="small" class="filter-item" type="primary" style="margin-left:10px;" @click="handleEdit">
                修改
              </el-button>
              <el-button size="small" class="filter-item" type="primary" style="margin-left:10px;" :loading="removeBtnLoading" @click="handleRemove">
                删除
              </el-button>
              <el-button size="small" class="filter-item" type="primary" style="margin-left:10px;" @click="handleDetail">
                详情
              </el-button>
            </el-col>
          </div>
        </div>
      </el-row>
    </div>
    <div class="grid-content bg-purple" />

    <div ref="box" class="box">
      <div class="left" :class="[isActive ? 'wid':'wids']">
        <div :class="[treeShow ? 'treeShow' : 'treeNotShow']" :style="{'height' : treeHeight + 'px'}">
          <AgencyTree class="agencyTree" @handleTreeQuery="handleTreeQuery" @getFirstAuthAgencyData="getFirstAuthAgencyData" />
        </div>
      </div>
      <div v-show="Show" class="resize" title="收缩侧边栏" />
      <div class="mid" :class="[isActive ? 'mids': 'min']">
        <div class="numCol">
          <span>单位名称：{{ unitName }} </span>
        </div>
        <!--表格部分-->
        <el-table
          ref="singleTable"
          v-loading="listLoading"
          :data="list"
          :stripe="true"
          fit
          :height="tableHeight"
          style="width:100%;"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80"
          />
          <el-table-column
            type="selection"
            align="center"
            width="55"
          />
          <el-table-column
            prop="salaryId"
            label="工资项名称"
            width="200"
          >
            <template slot-scope="{ row }">
              <span>{{ row.salaryId | salaryNameFilter(that) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="meritPayCode"
            label="工资类型"
            width="300"
          />
          <el-table-column
            prop="formula"
            label="公式"
          />
          <el-table-column
            prop="calcOrder"
            label="计算序号"
            align="center"
            width="120"
          />
        </el-table>
        <!--分页部分-->
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </div>
      <Drag ref="icon" />
    </div>
    <!--弹窗-->
    <el-dialog  v-dialogDrag  
      :close-on-click-modal="false"
      :width="operateType === 'detail' ? '35%' : '72%'"
      :title="dialogTitle"
      center
      :visible.sync="dialogFormVisible"
      @close="dialogClose"
      @opened="dialogOpened"
    >
      <el-row>
        <el-col :span="operateType === 'detail' ? 0 : 12">
          <el-row>
            <el-col :span="8">
              <!--查询所有工资项（包括计算项）-->
              <div
                class="salary-select"
                style="height:300px;"
              >
                <el-button
                  v-for="(item, index) in salaryList"
                  :key="item.id"
                  class="salary-option"
                  @click="selectSalary(index)"
                >{{ item.salaryName }}
                </el-button>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="keyboard">
                <!--虚拟键盘-->
                <el-row
                  v-for="(list, index) in keyList"
                  :key="index"
                >
                  <el-col
                    v-for="(item, indexInner) in list"
                    :key="indexInner"
                    :span="8"
                  >
                    <el-button
                      class="key-button"
                      @click="keydown(item)"
                    >{{
                      item
                    }}</el-button>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="operateType === 'detail' ? 24 : 12">
          <el-form
            ref="dialogForm"
            label-position="top"
            label-width="92px"
            :model="form"
            :rules="rules"
            inline
          >

            <el-form-item
              label="计算序号:"
              prop="calcOrder"
            >
              <el-input-number
                v-model="form.calcOrder"
                controls-position="right"
                :min="1"
                :max="99"
                :step="1"
                step-strictly
                :disabled="operateType === 'detail'"
              />
            </el-form-item>

            <el-form-item
              label="工资项:"
              prop="salaryId"
            >
              <el-select
                v-model="form.salaryId"
                style="width:50%;"
                placeholder="--请选择--"
                :disabled="operateType === 'detail' || operateType === 'edit'"
              >
                <template v-for="item in salaryList">
                  <el-option
                    v-if="item.isCompute === 1"
                    :key="item.id"
                    :label="item.salaryName"
                    :value="item.id"
                  />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item
              label="工资类别:"
              prop="meritPayCodeList"
            >
              <el-select v-model="form.meritPayCodeList" multiple placeholder="请选择">
                <el-option
                  v-for="item in meritPayCodes"
                  :key="item.code"
                  class="drag-select"
                  style="width:100%;"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="公式:"
              prop="inputFormula"
            >
              <el-input
                id="formulaTextarea"
                v-model="form.inputFormula"
                type="textarea"
                :rows="6"
                :maxlength="0"
                style="width:411px;"
                :disabled="operateType === 'detail'"
                oncontextmenu="return false;"
                ondragstart="return false;"
              />
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          v-if="operateType === 'add' || operateType === 'edit'"
          @click="handleCancel"
        >取消</el-button>
        <el-button
          v-if="operateType === 'detail'"
          @click="handleCancel"
        >关闭</el-button>
        <el-button
          v-if="operateType === 'add' || operateType === 'edit'"
          type="primary"
          :loading="saveBtnLoading"
          @click="handleSave"
        >保存</el-button>
      </div>
    </el-dialog>



    
<!-- 复制公式 -->
      <el-dialog  v-dialogDrag  
       :close-on-click-modal="false"
        :width=" '52%'"
        title="复制公式"
        center
        :visible.sync="dialogFormCopyFormula"
    >
     <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
       
        label-position="right"
        label-width="0px"
      >
         <div style="height:500px;overflow:auto;">
            <el-tree
              id="onlyLeafShow"
              ref="tree"
              node-key="id"
              show-checkbox
              :highlight-current="true"
              :data="agencyTreeData"
              :props="defaultProps"
              :default-expanded-keys="['0']"
              :filter-node-method="filterNode"
               @handleTreeQuery="handleTreeQuery"
              @getFirstAuthAgencyData="getFirstAuthAgencyData" 
            />
          </div>
          <!-- <AgencyTree 
           class="agencyTree"
           show-checkbox
           ref="tree"
           @handleTreeQuery="handleTreeQuery" 
           @getFirstAuthAgencyData="getFirstAuthAgencyData" 

           
           /> -->
          <el-button
            type="primary"
            style="float:right;"
             :loading="verifyLoading"
            @click="batchHandleAudit"
          >
            复制公式
          </el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  submitData,
  getAllSalary,
  getFormulaDetail,
  queryFormulaManagePage,
  removeFormulaById,
  saveCopyFormula
} from '@/api/salaryConfigManage/formulaManage'
import Pagination from '@/components/Pagination'
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
import {getSalaryType} from '@/api/baseInfo'
import { getAuthAgencyTree, getFirstAuthAgencyData } from '@/api/baseInfo'
const chReg = /^[\u4e00-\u9fa5]$/
const reg1 = /^\s$/
const reg2 = /^\[$/
const reg3 = /^]$/
const reg4 = /^\($/
const reg5 = /^\)$/

export default {
  name: 'FormulaManage',
  components: { Pagination, tableEmpty, AgencyTree, Drag },
  filters: {
    salaryNameFilter(value, that) {
      return that.salaryIdMap[value]
    }
  },
  data() {
    const evil = fn => {
      // 一个变量指向Function，防止有些前端编译工具报错
      const Fn = Function
      return new Fn('return ' + fn)()
    }
    // 公式可行性校验
    const formulaExecuteVerify = (rule, value, callback) => {
      const formula = value.replace(/\s\[.+?]\s/g, ' 1 ')
      try {
        evil(formula)
        callback()
      } catch (err) {
        callback(new Error('该公式不可被执行'))
      }
    }
    return {
      meritPayCodes: [
        { value: '0', label: '行政人员' },
        { value: '1', label: '事业人员' },
        { value: '11', label: '离退休人员' }
      ],
      treeHeight: null,
      isActive: true,
      Show: false,
      treeShow: false,
      unitName: '预算单位',
      treeData: '',
      tableHeight: null,
      dialogEditFormVisible: false,
      dialogStatus: '',
      that: this,
      dialogTitle: '',
      operateType: '', // 当前操作状态（新增，编辑，详情）
      list: [],
      total: 0,
      listLoading: false,
      verifyLoading: false,
      saveBtnLoading: false,
      removeBtnLoading: false,
      dialogFormCopyFormula:false,
      agencyTreeData: [],
       defaultProps: {
        children: 'children',
        label: 'label'
      },
      listQuery: {
        page: 1,
        limit: 200,
        agencyId: null
      },
      queryForm: {
        salaryId: ''
      },
      dialogFormVisible: false,
      agencyId: null,
      form: {
        id: '',
        calcOrder: '',
        salaryId: '',
        formula: '',
        inputFormula: '',
        meritPayCodeList: ''
      },
      rules: {
        calcOrder: [
          { required: true, message: '请输入计算序号', trigger: 'blur' }
        ],
        salaryId: [
          { required: true, message: '请选择工资项', trigger: 'change' }
        ],
        inputFormula: [
          { required: true, message: '请输入公式', trigger: 'blur' },
          { validator: formulaExecuteVerify, trigger: 'change' }
        ],
        meritPayCodeList: [
          { required: true, message: '请选择工资类别', trigger: 'blur' }
        ]
      },
      salaryList: [],
      salaryNameMap: {}, // 工资名称对应工资id
      salaryIdMap: {}, // 工资id对应工资名称
      keyList: [
        ['+', '-', '*'],
        ['/', '(', ')'],
        ['7', '8', '9'],
        ['4', '5', '6'],
        ['1', '2', '3'],
        ['%', '0', '.']
      ]
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    },
    treeData(val) {
      if (val && val.isleaf === '1') {
        this.unitName = this.treeData.label.split('-')[1]
        this.handleTree(val)
      }
    }
  },
  created() {
     this.getTreeData()
    this.getFirstAuthAgencyData()
    if (this.treeData && this.treeData.isleaf === '1') {
      this.unitName = this.treeData.label.split('-')[1]
      this.listQuery.agencyId = this.treeData.id
      this.agencyId = this.treeData.id
      this.handleFilter()
    }
  },
  mounted() {
    this.dragController()
    this.getTeHeight()
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
    window.addEventListener('resize', this.getTeHeight)
  },
  methods: {
      getTreeData() {
      getAuthAgencyTree().then(response => {
        this.agencyTreeData = response.data
      })
    },
    getFirstAuthAgencyData(data) {
      this.treeData = data
    },
    getTeHeight() {
      this.treeHeight = window.innerHeight - 250
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 250
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
     filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    handleTreeQuery(data) {
      if (data && data.isleaf === '1') {
        this.treeData = data
      }
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 查询
    Query() {
      if (this.treeData && this.treeData.isleaf === '1') {
        this.dialogStatus = '公式管理'
        this.dialogEditFormVisible = true
      }
    },
    getAllSalary() {
      // 获取所有工资项
      return getAllSalary().then(res => {
        this.salaryList = res.data
        for (const salary of this.salaryList) {
          this.salaryNameMap[salary.salaryName] = salary.id
          this.salaryIdMap[salary.id] = salary.salaryName
        }
      })
    },
    handleTree(data) {
      this.listQuery.agencyId = data.id
      this.agencyId = data.id
      this.handleFilter()
    },
    handleFilter() {
      this.dialogStatus = '公式管理'
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getAllSalary().then(() => {
        this.getList()
      })
      this.dialogEditFormVisible = false
    },
    getList() {
      this.listLoading = true
      Object.assign(this.listQuery, this.queryForm)
      queryFormulaManagePage(this.listQuery)
        .then(res => {
          const rows = res.data.rows
          for (const row of rows) {
            const args = row.formula.split(',')
            let formula = ''
            for (let arg of args) {
              if (arg.startsWith('&') && arg.endsWith('&')) {
                arg = arg.substring(1, arg.length - 1)
                formula += ' [' + this.salaryIdMap[arg] + '] '
              } else {
                formula += arg
              }
            }
            row.formula = formula
          }
          this.list = rows
          this.total = res.data.total
          this.initData()
        })
        .catch(() => {
          this.initData()
        })
    },
    initData() {
      this.listLoading = false
      getSalaryType().then(response => {
        this.meritPayCodes = Object.assign({}, response.data)
      })
    },
    dialogClose() {
      this.handleCancel()
    },
    /**
     *自定义键盘退格键删除
     */
    dialogOpened() {
      const formulaTextarea = document.getElementById('formulaTextarea')
      formulaTextarea.onkeydown = event => {
        // 自定义回退键删除事件
        if (event.code === 'Backspace') {
          let startPos = formulaTextarea.selectionStart
          const endPos = formulaTextarea.selectionEnd
          if (startPos === undefined || endPos === undefined) return
          const txt = formulaTextarea.value
          let result = ''
          if (startPos !== endPos) {
            let str1 = ''
            let str2 = ''
            const fontStr = txt.substring(0, startPos)
            const backStr = txt.substring(endPos)
            // 被删除字符串的第一个字符
            const startChar = txt.substring(startPos, startPos + 1)
            // 被删除字符串的最后一个字符
            const endChar = txt.substring(endPos - 1, endPos)
            // 判断第一个字符
            if (
              chReg.test(startChar) ||
              reg2.test(startChar) ||
              reg3.test(startChar)
            ) {
              str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
            } else if (reg1.test(startChar)) {
              // 如果是空格的话，需要判断光标前的字符是否是】或【
              const char = txt.substring(startPos - 1, startPos)
              if (reg3.test(char) || reg2.test(char)) {
                str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
              } else {
                str1 = txt.substring(0, startPos)
              }
            } else if (reg4.test(startChar) || reg5.test(startChar)) {
              // 如果是小括号的话，需要判断光标前或后的字符是否是汉字
              const char1 = txt.substring(startPos - 1, startPos)
              const char2 = txt.substring(startPos + 1, startPos + 2)
              if (chReg.test(char1) || chReg.test(char2)) {
                str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
              } else {
                str1 = txt.substring(0, startPos)
              }
            } else {
              str1 = txt.substring(0, startPos)
            } // 判断最后一个字符
            if (
              chReg.test(endChar) ||
              reg2.test(endChar) ||
              reg3.test(endChar)
            ) {
              str2 = backStr.substring(backStr.indexOf(' ') + 1)
            } else if (reg1.test(endChar)) {
              const char = txt.substring(endPos, endPos + 1)
              // 如果是空格的话，需要判断光标后的字符是否是【或】
              if (reg3.test(char) || reg2.test(char)) {
                str2 = backStr.substring(backStr.indexOf(' ') + 1)
              } else {
                str2 = txt.substring(endPos)
              }
            } else if (reg4.test(endChar) || reg5.test(endChar)) {
              // 如果是小括号的话，需要判断光标前或后的字符是否是汉字
              const char1 = txt.substring(endPos - 1, endPos)
              const char2 = txt.substring(endPos, endPos + 1)
              if (chReg.test(char1) || chReg.test(char2)) {
                str2 = backStr.substring(backStr.indexOf(' ') + 1)
              } else {
                str2 = txt.substring(endPos)
              }
            } else {
              str2 = txt.substring(endPos)
            }
            result = str1 + str2
            startPos = str1.length
          } else {
            const fontStr = txt.substring(0, startPos - 1)
            const backStr = txt.substring(startPos)
            // 被删除的字符
            const delChar = txt.substring(startPos - 1, startPos)
            // 判断字符
            if (
              chReg.test(delChar) ||
              reg2.test(delChar) ||
              reg3.test(delChar)
            ) {
              result =
                fontStr.substring(0, fontStr.lastIndexOf(' ')) +
                backStr.substring(backStr.indexOf(' ') + 1)
              startPos = fontStr.lastIndexOf(' ')
            } else if (reg1.test(delChar)) {
              const char = txt.substring(startPos - 2, startPos - 1)
              if (reg3.test(char)) {
                // 工资项尾部空格
                result =
                  fontStr.substring(0, fontStr.lastIndexOf(' ')) + backStr
                startPos = fontStr.lastIndexOf(' ')
              } else {
                // 工资项首部空格
                result = fontStr + backStr.substring(backStr.indexOf(' ') + 1)
                startPos = fontStr.length
              }
            } else if (reg4.test(delChar) || reg5.test(delChar)) {
              const char1 = txt.substring(startPos - 1, startPos)
              const char2 = txt.substring(startPos + 1, startPos + 2)
              if (chReg.test(char1) || chReg.test(char2)) {
                result =
                  fontStr.substring(0, fontStr.lastIndexOf(' ')) +
                  backStr.substring(backStr.indexOf(' ') + 1)
                startPos = fontStr.lastIndexOf(' ')
              } else {
                result = fontStr + backStr
                startPos = fontStr.length
              }
            } else {
              result = fontStr + backStr
              startPos = fontStr.length
            }
          }
          formulaTextarea.value = result
          this.form.inputFormula = result
          // 重新定义光标位置
          formulaTextarea.focus()
          formulaTextarea.selectionStart = startPos
          formulaTextarea.selectionEnd = startPos
        }
        return false
      }
    },
    /**
     *点击虚拟键盘
     */
    keydown(key) {
      const formulaTextarea = document.getElementById('formulaTextarea')
      let startPos = formulaTextarea.selectionStart
      const endPos = formulaTextarea.selectionEnd
      if (startPos === undefined || endPos === undefined) return
      const txt = formulaTextarea.value
      let result = ''
      if (startPos !== endPos) {
        let str1 = ''
        let str2 = ''
        const fontStr = txt.substring(0, startPos)
        const backStr = txt.substring(endPos)
        // 被选中字符串的第一个字符
        const startChar = txt.substring(startPos, startPos + 1)
        // 被选中字符串的最后一个字符
        const endChar = txt.substring(endPos - 1, endPos)
        // 判断第一个字符
        if (
          chReg.test(startChar) ||
          reg2.test(startChar) ||
          reg3.test(startChar)
        ) {
          str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
        } else if (reg1.test(startChar)) {
          // 如果是空格的话，需要判断光标前的字符是否是】或【
          const char = txt.substring(startPos - 1, startPos)
          if (reg3.test(char) || reg2.test(char)) {
            str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
          } else {
            str1 = txt.substring(0, startPos)
          }
        } else if (reg4.test(startChar) || reg5.test(startChar)) {
          // 如果是小括号的话，需要判断光标前或后的字符是否是汉字
          const char1 = txt.substring(startPos - 1, startPos)
          const char2 = txt.substring(startPos + 1, startPos + 2)
          if (chReg.test(char1) || chReg.test(char2)) {
            str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
          } else {
            str1 = txt.substring(0, startPos)
          }
        } else {
          str1 = txt.substring(0, startPos)
        } // 判断最后一个字符
        if (chReg.test(endChar) || reg2.test(endChar) || reg3.test(endChar)) {
          str2 = backStr.substring(backStr.indexOf(' ') + 1)
        } else if (reg1.test(endChar)) {
          const char = txt.substring(endPos, endPos + 1)
          // 如果是空格的话，需要判断光标后的字符是否是【或】
          if (reg3.test(char) || reg2.test(char)) {
            str2 = backStr.substring(backStr.indexOf(' ') + 1)
          } else {
            str2 = txt.substring(endPos)
          }
        } else if (reg4.test(endChar) || reg5.test(endChar)) {
          // 如果是小括号的话，需要判断光标前或后的字符是否是汉字
          const char1 = txt.substring(endPos - 1, endPos)
          const char2 = txt.substring(endPos, endPos + 1)
          if (chReg.test(char1) || chReg.test(char2)) {
            str2 = backStr.substring(backStr.indexOf(' ') + 1)
          } else {
            str2 = txt.substring(endPos)
          }
        } else {
          str2 = txt.substring(endPos)
        }
        result = str1 + key + str2
        startPos = str1.length + key.length
      } else {
        const fontStr = txt.substring(0, startPos)
        const backStr = txt.substring(startPos)
        // 获取光标前后字符
        const startChar = txt.substring(startPos - 1, startPos)
        const endChar = txt.substring(startPos, startPos + 1)
        // 前后都是汉字
        if (
          (chReg.test(startChar) && chReg.test(endChar)) ||
          // 前是汉字，后是中括号】
          (chReg.test(startChar) && reg3.test(endChar)) ||
          // 前是中括号【，后是汉字
          (reg2.test(startChar) && chReg.test(endChar)) ||
          // 前是空格，后是中括号【
          (reg1.test(startChar) && reg2.test(endChar)) ||
          // 前是中括号】，后是空格
          (reg3.test(startChar) && reg1.test(endChar)) ||
          // 前是汉字或【，后是小括号（
          ((chReg.test(startChar) || reg2.test(startChar)) &&
            reg4.test(endChar)) ||
          // 前是小括号（，后是汉字或】
          (reg4.test(startChar) &&
            (chReg.test(endChar) || reg3.test(endChar))) ||
          // 前是汉字或【，后是小括号）
          ((chReg.test(startChar) || reg2.test(startChar)) &&
            reg5.test(endChar)) ||
          // 前是小括号），后是汉字或】
          (reg5.test(startChar) && (chReg.test(endChar) || reg3.test(endChar)))
        ) {
          result =
            fontStr.substring(0, fontStr.lastIndexOf(' ')) +
            key +
            backStr.substring(backStr.indexOf(' ') + 1)
          startPos = fontStr.lastIndexOf(' ') + key.length
        } else {
          result = fontStr + key + backStr
          startPos = fontStr.length + key.length
        }
      }
      formulaTextarea.value = result
      this.form.inputFormula = result
      // 赋值给表单中的的字段//重新定义光标位置
      formulaTextarea.focus()
      formulaTextarea.selectionStart = startPos
      formulaTextarea.selectionEnd = startPos
    },
    /**
     *点选工资项
     */
    selectSalary(index) {
      const salaryName = ' [' + this.salaryList[index].salaryName + '] '
      const formulaTextarea = document.getElementById('formulaTextarea')
      let startPos = formulaTextarea.selectionStart
      const endPos = formulaTextarea.selectionEnd
      if (startPos === undefined || endPos === undefined) return
      const txt = formulaTextarea.value
      let result = ''
      if (startPos !== endPos) {
        let str1 = ''
        let str2 = ''
        const fontStr = txt.substring(0, startPos)
        const backStr = txt.substring(endPos)
        // 被选中字符串的第一个字符
        const startChar = txt.substring(startPos, startPos + 1)
        // 被选中字符串的最后一个字符
        const endChar = txt.substring(endPos - 1, endPos)
        // 判断第一个字符
        if (
          chReg.test(startChar) ||
          reg2.test(startChar) ||
          reg3.test(startChar)
        ) {
          str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
        } else if (reg1.test(startChar)) {
          // 如果是空格的话，需要判断光标前的字符是否是】或【
          const char = txt.substring(startPos - 1, startPos)
          if (reg3.test(char) || reg2.test(char)) {
            str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
          } else {
            str1 = txt.substring(0, startPos)
          }
        } else if (reg4.test(startChar) || reg5.test(startChar)) {
          // 如果是小括号的话，需要判断光标前或后的字符是否是汉字
          const char1 = txt.substring(startPos - 1, startPos)
          const char2 = txt.substring(startPos + 1, startPos + 2)
          if (chReg.test(char1) || chReg.test(char2)) {
            str1 = fontStr.substring(0, fontStr.lastIndexOf(' '))
          } else {
            str1 = txt.substring(0, startPos)
          }
        } else {
          str1 = txt.substring(0, startPos)
        } // 判断最后一个字符
        if (chReg.test(endChar) || reg2.test(endChar) || reg3.test(endChar)) {
          str2 = backStr.substring(backStr.indexOf(' ') + 1)
        } else if (reg1.test(endChar)) {
          const char = txt.substring(endPos, endPos + 1)
          // 如果是空格的话，需要判断光标后的字符是否是【或】
          if (reg3.test(char) || reg2.test(char)) {
            str2 = backStr.substring(backStr.indexOf(' ') + 1)
          } else {
            str2 = txt.substring(endPos)
          }
        } else if (reg4.test(endChar) || reg5.test(endChar)) {
          // 如果是小括号的话，需要判断光标前或后的字符是否是汉字
          const char1 = txt.substring(endPos - 1, endPos)
          const char2 = txt.substring(endPos, endPos + 1)
          if (chReg.test(char1) || chReg.test(char2)) {
            str2 = backStr.substring(backStr.indexOf(' ') + 1)
          } else {
            str2 = txt.substring(endPos)
          }
        } else {
          str2 = txt.substring(endPos)
        }
        result = str1 + salaryName + str2
        startPos = str1.length + salaryName.length
      } else {
        const fontStr = txt.substring(0, startPos)
        const backStr = txt.substring(startPos)
        // 获取光标前后字符
        const startChar = txt.substring(startPos - 1, startPos)
        const endChar = txt.substring(startPos, startPos + 1)
        // 前后都是汉字
        if (
          (chReg.test(startChar) && chReg.test(endChar)) ||
          // 前是汉字，后是中括号】
          (chReg.test(startChar) && reg3.test(endChar)) ||
          // 前是中括号【，后是汉字
          (reg2.test(startChar) && chReg.test(endChar)) ||
          // 前是空格，后是中括号【
          (reg1.test(startChar) && reg2.test(endChar)) ||
          // 前是中括号】，后是空格
          (reg3.test(startChar) && reg1.test(endChar)) ||
          // 前是汉字或【，后是小括号（
          ((chReg.test(startChar) || reg2.test(startChar)) &&
            reg4.test(endChar)) ||
          // 前是小括号（后是汉字或】
          (reg4.test(startChar) &&
            (chReg.test(endChar) || reg3.test(endChar))) ||
          // 前是汉字或【，后是小括号）
          ((chReg.test(startChar) || reg2.test(startChar)) &&
            reg5.test(endChar)) ||
          // 前是小括号），后是汉字或】
          (reg5.test(startChar) && (chReg.test(endChar) || reg3.test(endChar)))
        ) {
          result =
            fontStr.substring(0, fontStr.lastIndexOf(' ')) +
            salaryName +
            backStr.substring(backStr.indexOf(' ') + 1)
          startPos = fontStr.lastIndexOf(' ') + salaryName.length
        } else {
          result = fontStr + salaryName + backStr
          startPos = fontStr.length + salaryName.length
        }
      }
      formulaTextarea.value = result
      this.form.inputFormula = result
      // 赋值给表单中的的字段 //重新定义光标位置
      formulaTextarea.focus()
      formulaTextarea.selectionStart = startPos
      formulaTextarea.selectionEnd = startPos
    },

    handleCancel() {
      this.$refs.dialogForm.resetFields()
      this.resetForm()
      this.dialogFormVisible = false
    },

    resetForm() {
      this.form = {
        id: '',
        calcOrder: '',
        salaryId: '',
        formula: '',
        inputFormula: '',
        meritPayCodeList: ''
      }
    },

    handleSave() {
      this.$refs.dialogForm.validate(valid => {
        // 表单规则校验
        if (valid) {
          this.saveBtnLoading = true
          // this.$confirm('确定保存吗？', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
          // 处理输入的公式，
          const argList = []
          const formula = this.form.inputFormula
          // formula=formula.replace(/([\+\-\*\/\(\)%])/g,'$1');
          const args = formula.split(' ')
          for (let arg of args) {
            if (arg.startsWith('[') && arg.endsWith(']')) {
              arg = arg.substring(1, arg.length - 1)
              const salaryId = this.salaryNameMap[arg]
              argList.push('&' + salaryId + '&')
            } else {
              arg = arg.replace(/([\+\-\*\/\(\)%])/g, ' $1 ')
              const symbols = arg.split(' ')
              for (const symbol of symbols) {
                if (symbol !== '') {
                  argList.push(symbol)
                }
              }
            }
          }
          this.form.agencyId = this.agencyId
          this.form.formula = argList.join(',')
          // return
         // console.log(this.form)
          submitData(this.form).then(() => {
            this.$message({
              message: '保存成功',
              type: 'success',
              showClose: true,
              duration: 4000
            })
            this.handleCancel()
            this.saveBtnLoading = false
            this.handleFilter()
          }).catch(() => {
            this.saveBtnLoading = false
          })
          // }).catch(() => {
          //   this.saveBtnLoading = false
          // })
        } else {
          this.saveBtnLoading = false
        }
      })
    },

    handleAdd() {
      if (!this.treeData || this.treeData.isleaf !== '1') {
        return
      }
      this.form.id = null
      this.operateType = 'add'
      this.dialogTitle = '新增'
      this.dialogFormVisible = true
    },

    handleEdit() {
      if (!this.treeData || this.treeData.isleaf !== '1') {
        return
      }
      const selection = this.$refs.singleTable.selection
      if (selection.length !== 1) {
        this.$message({
          message: '请选择一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      // 对form赋值
      getFormulaDetail(selection[0].id).then(res => {
        const formulaDetail = res.data
        const args = formulaDetail.formula.split(',')
        let formula = ''
        for (let arg of args) {
          if (arg.startsWith('&') && arg.endsWith('&')) {
            arg = arg.substring(1, arg.length - 1)
            formula += ' [' + this.salaryIdMap[arg] + '] '
          } else {
            formula += arg
          }
        }
        this.form = {
          id: formulaDetail.id,
          updateTime: formulaDetail.updateTime,
          createTime: formulaDetail.createTime,
          salaryId: formulaDetail.salaryId,
          formula: formula,
          inputFormula: formula,
          openType: formulaDetail.openType,
          calcOrder: formulaDetail.calcOrder,
          isDeleted: formulaDetail.isDeleted,
          meritPayCodeList: formulaDetail.meritPayCodeList
        }
        this.operateType = 'edit'
        this.dialogTitle = '编辑'
        this.dialogFormVisible = true
      })
    },
    handleRemove() {
      if (!this.treeData || this.treeData.isleaf !== '1') {
        return
      }
      this.removeBtnLoading = true
      const selection = this.$refs.singleTable.selection
      if (selection.length !== 1) {
        this.$message({
          message: '请选择一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        this.removeBtnLoading = false
        return
      }
      this.$confirm('确定删除吗?', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeFormulaById(selection[0].id)
            .then(res => {
              this.$message({
                message: '删除成功',
                type: 'success',
                showClose: true,
                duration: 4000
              })
              this.handleFilter()
              this.removeBtnLoading = false
            })
            .catch(() => {
              this.removeBtnLoading = false
            })
        })
        .catch(() => {
          this.removeBtnLoading = false
        })
    },
    handleDetail() {
      if (!this.treeData || this.treeData.isleaf !== '1') {
        return
      }
      const selection = this.$refs.singleTable.selection
      if (selection.length !== 1) {
        this.$message({
          message: '请选择一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      // 对form赋值
      getFormulaDetail(selection[0].id).then(res => {
        const formulaDetail = res.data
        const args = formulaDetail.formula.split(',')
        let formula = ''
        for (let arg of args) {
          if (arg.startsWith('&') && arg.endsWith('&')) {
            arg = arg.substring(1, arg.length - 1)
            formula += ' [' + this.salaryIdMap[arg] + '] '
          } else {
            formula += arg
          }
        }
        this.form = {
          id: formulaDetail.id,
          updateTime: formulaDetail.updateTime,
          createTime: formulaDetail.createTime,
          salaryId: formulaDetail.salaryId,
          formula: formula,
          inputFormula: formula,
          openType: formulaDetail.openType,
          calcOrder: formulaDetail.calcOrder,
          isDeleted: formulaDetail.isDeleted
        }
        this.operateType = 'detail'
        this.dialogTitle = '预览'
        this.dialogFormVisible = true
      })
    },
     CopyFormula(){
       this.getTreeData()
       this.dialogFormCopyFormula = true

    },
    batchHandleAudit(){
     
      const allAgencyId = this.$refs.tree.getCheckedKeys(true)
       if (allAgencyId.length === 0) {
        this.$message({
          message: '请选择至少选择一个单位',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
         this.verifyLoading = true
      this.form.agencyId = this.agencyId
      const params = {}
      params['agencyIds'] = allAgencyId
      params['agencyId'] = this.agencyId
      console.log(params)
       saveCopyFormula(params)
       .then(() => {
            this.$message({
              message: '保存成功',
              type: 'success',
              showClose: true,
              duration: 4000
            })
            this.verifyLoading = false
            this.dialogFormCopyFormula = false 
          }).catch(() => {
            this.verifyLoading = false
          })
       
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/border.scss"; /*引入公共样式*/
.salary-select {
  height: 300px;
  overflow: scroll;
  overflow-x: hidden;

  .salary-option {
    height: 30px;
    width: 100%;
    margin-left: 0;
  }
}

.keyboard {
  height: 300px;
  padding: 0 32px;

  .el-col {
    text-align: center;
  }

  .key-button {
    height: 36px;
    width: 56px;
    margin: 6px;
  }
}

.app-title {
  margin-bottom: 15px;
  height: 20px;
  border-bottom: 1px solid #dcdfe6;
}

  .numCol {
    margin-top: 10px;
    span {
      font-size: 14px;
    }
  }

.drag-select {
  ::v-deep {
    .sortable-ghost {
      opacity: .8;
      color: #fff !important;
      background: #42b983 !important;
    }

    .el-tag {
      cursor: pointer;
    }
  }
}
::v-deep .el-select {
  .el-input {
    height: auto !important;
  }
}
</style>
